<template>
  <view class="num-keyboard">
    <!-- <view class="num-keyboard-input padding margin-bottom">{{userInput}}</view> -->
    <view class="num-keyboard-key grid col-3">
      <button class="keyboard" v-for="(item,index) in keyList" :key="index"
        @click="onkeydown(item,index)">{{item}}</button>
    </view>
  </view>
</template>

<script>
  export default {
    name: "g-num-keyboard",
    data() {
      return {
        keyList: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '·', '0', '退格'],
        userInput: "",
      };
    },
    props: {
      defaultValue: {
        type: [Number, String],
        default: 0
      }
    },
    computed: {
      userValue: function() {
        let val = this.userInput
        if (val.indexOf(".") == (val.length - 1)) {
          val = val.substr(0, val.length - 1)
        }
        console.log("userValue,", Number(val))
        return Number(val)
      }
    },
    methods: {
      onkeydown(e) {
        let value = this.userInput
        let val = e

        if (value.indexOf(".") == -1) {
          if (val !== '退格') {
            if (val == '·') {
              value = value + '.'
            } else {
              value = value + val
            }

          } else if (value) {
            value = value.substr(0, value.length - 1)
          }
          this.userInput = value
        } else if (e !== "·") {
          if (val !== '退格') {
            value = value + val

          } else if (value) {
            value = value.substr(0, value.length - 1)
          }
          this.userInput = value
        }

        let exportval = this.userInput
        if (exportval.indexOf(".") == (exportval.length - 1)) {
          exportval = exportval.substr(0, exportval.length - 1)
        }
        this.$emit('on-value-change', Number(exportval))
        // console.log("userValue,",Number(exportval))
      }
    },
    watch: {
      "defaultValue": {
        handler: function(newVal, oldVal) {
          if (newVal !== oldVal) {
            this.userInput = "" + newVal
          }
        }
      }
    }
  }
</script>

<style lang="scss" scoped>
  .num-keyboard {
    .num-keyboard-input {
      height: 3vh;
      line-height: 3vh;
      background-color: #f3f3f3;
      width: 100%;
    }

    .num-keyboard-key {
      min-height: 20vh;

      .keyboard {
        width: 30%;
        // height:100%;
        min-height: 8vh;
        font-weight: bold;
        color: #000;
        margin-bottom: 10rpx;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
  }
</style>
